/* eslint-disable @typescript-eslint/no-use-before-define */
import { DictValueEnum } from "@/components/DictTag";
import { getRole } from "@/services/api/module/system/role";
import { ModalForm, ProFormDigit, ProFormInstance, ProFormRadio, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import React, { useEffect, useRef, useState } from "react";
import { formTitle } from "../contents";
export type RoleFormData = Record<string, unknown> & Partial<API.Setting.RoleBo>;
export type RoleFormProps = {
	onCancel: (flag?: boolean) => void;
	onSubmit: (values: RoleFormData) => Promise<any>;
	open: boolean;
	id: number | undefined;
	statusOptions: DictValueEnum;
};
const RoleForm: React.FC<RoleFormProps> = props => {
	// 国际化
	const formRef = useRef<ProFormInstance>();
	const { statusOptions, id, onCancel, onSubmit, open } = props;
	// 初始化
	useEffect(() => {
		formRef?.current?.resetFields();
		if (id) {
			setFormValue(id);
		}
	}, [id]);
	// 表单赋值
	const setFormValue = (id: number) => {
		getRole(id).then(res => {
			formRef?.current?.setFieldsValue(res);
		});
	};
	// 关闭
	const handleCancel = () => {
		onCancel();
	};
	// 表单提交
	const handleFinish = async (values: RoleFormData) => {
		return onSubmit({
			...values,
			id: id ? id : undefined
		} as RoleFormData);
	};

	return (
		<ModalForm<RoleFormData>
			width={600}
			title={id ? formTitle[1] : formTitle[0]}
			open={open}
			formRef={formRef}
			grid={true}
			layout="vertical"
			modalProps={{
				destroyOnClose: true,
				onCancel: () => {
					handleCancel();
				}
			}}
			onFinish={handleFinish}
		>
			<ProFormText
				name="roleName"
				label="角色名称"
				placeholder="请输入角色名称"
				rules={[
					{
						required: true,
						message: "请输入角色名称！"
					}
				]}
			/>
			<ProFormText
				name="roleKey"
				label="角色编码"
				tooltip="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)"
				placeholder="请输入角色编码"
				rules={[
					{
						required: true,
						message: "请输入角色编码！"
					}
				]}
			/>
			<ProFormDigit
				name="sort"
				label="显示顺序"
				placeholder="请输入显示顺序"
				rules={[
					{
						required: true,
						message: "请输入显示顺序！"
					}
				]}
				initialValue={0}
			/>
			<ProFormRadio.Group
				valueEnum={statusOptions}
				name="status"
				label="角色状态"
				initialValue={"0"}
				placeholder="请输入角色状态"
				rules={[
					{
						required: true,
						message: "请输入角色状态！"
					}
				]}
			/>
			<ProFormTextArea name="remark" label="备注" placeholder="请输入备注" />
		</ModalForm>
	);
};

export default RoleForm;
